using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using NuSoft.Business;

namespace NSFxSamples.CRUD
{
	public partial class Default : Page
	{
		private const string ADD_NEW_TEXT = "- Add New Department -";
		private const string ADD_NEW_VALUE = "-1";


		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				PopulateDepartmentList();
			}
		}


		protected void ddlDepartmentNames_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (ddlDepartmentNames.SelectedValue == ADD_NEW_VALUE)
			{
				ResetPage();
			}
			else
			{
				BindDepartmentToForm(GetSelectedDepartment());

				btnDelete.Visible = true;
			}
		}


		protected void btnSubmit_Click(object sender, EventArgs e)
		{
			SaveDepartment(GetSelectedDepartment());

			ResetPage();
		}


		protected void btnDelete_Click(object sender, EventArgs e)
		{
			GetSelectedDepartment().Delete();

			ResetPage();
		}


		private Department GetSelectedDepartment()
		{
			Department department;

			if (ddlDepartmentNames.SelectedValue == ADD_NEW_VALUE)
			{
				department = Department.CreateDepartment();
			}
			else
			{
				department = Department.GetDepartment(short.Parse(ddlDepartmentNames.SelectedValue));
			}

			return department;
		}


		private void SaveDepartment(Department department)
		{
			department.Name = txtName.Text;
			department.GroupName = txtGroupName.Text;

			department.Save();
		}


		private void PopulateDepartmentList()
		{
			ddlDepartmentNames.Items.Clear();

			foreach (Department department in Department.GetDepartments())
			{
				ListItem departmentItem = new ListItem(department.Name, department.DepartmentID.ToString());

				ddlDepartmentNames.Items.Add(departmentItem);
			}

			ListItem newDepartmentItem = new ListItem(ADD_NEW_TEXT, ADD_NEW_VALUE);

			ddlDepartmentNames.Items.Insert(0, newDepartmentItem);
		}


		private void BindDepartmentToForm(Department department)
		{
			txtName.Text = department.Name;
			txtGroupName.Text = department.GroupName;
		}


		private void ResetPage()
		{
			Response.Redirect(Request.Url.ToString());
		}
	}
}